<?php
/**
 * this class provides functions for encrypt end decrypt a string by a key
 * and parses and encrypted query string to decrypt string
 * 
 * @author		simon ungerboeck <ungerboeck_simon@hotmail.com>
 * @version		1.0
 */

define('STANDARD_ENCRYPTION', 'alskdfj1foaaAWDF1k1af91ASF11922FJ11234fDkr1');

class Cryptic
{


	/**
	 * encrypts a text and binds text to given key
	 * @param 		string		 $string
	 * @param 		string		 $key
	 * @return		string		 $result
	 */
	public static function encrypt($string, $key = null)
	{
		$key = ($key != null) ? $key : STANDARD_ENCRYPTION;
		$result='';
		for($i=0; $i < strlen($string); $i++)
		{
			$char=substr($string, $i, 1);
			$keychar=substr($key, ($i % strlen($key)) - 1, 1);
			$char=chr(ord($char) + ord($keychar));
			$result.=$char;
		}
		return base64_encode($result);
	}


	/**
	 * decrypts a text by given key
	 * @param 		string		 $string
	 * @param 		string		 $key
	 * @return		string		 $result
	 */
	public static function decrypt($string, $key = null)
	{
		$key = ($key != null) ? $key : STANDARD_ENCRYPTION;
		$result='';
		$string=base64_decode($string);
		
		for($i=0; $i < strlen($string); $i++)
		{
			$char=substr($string, $i, 1);
			$keychar=substr($key, ($i % strlen($key)) - 1, 1);
			$char=chr(ord($char) - ord($keychar));
			$result.=$char;
		}
		return $result;
	}
	
	
	/**
	 * returns decrypted query param
	 * @param 		string		$queryParam
	 * @return		string		
	 */
	public static function getQueryParam($queryParam, $key = null){
		$params = array();
		$key = ($key != null) ? $key : STANDARD_ENCRYPTION;
		$queryString = self::decrypt($_SERVER['QUERY_STRING'], $key);
		parse_str($queryString, $params);
		return $params[$queryParam];
	}
	
	
	/**
	 * encryptes a given file
	 * @param		string		$path
	 * @param		string		$file
	 * @param		string		$key
	 */
	public static function encryptFile($path, $file, $key = null){
		$key = ($key != null) ? $key : STANDARD_ENCRYPTION;
		
		$fr = new FileReader($path, $file, 'rb');
		$content = $fr->readFile();
		$content = Cryptic::encrypt($content, $key);
		
		$fw = new FileWriter($path, $file, 'wb');
		$fw->writeLine($content);
	}
	
	
	public function decryptFile($path, $file, $key){
		$key = ($key != null) ? $key : STANDARD_ENCRYPTION;
		
		$fr = new FileReader($path, $file, 'rb');
		$content = $fr->readFile();
		$content = Cryptic::decrypt($content, $key);
		return $content;
	}
}
?>